﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace AdbRegisterTool
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {

        private string _reg_add_one;
        private string _reg_add_two;
        private string _reg_add_three;
        private string _reg_add_four;
        private string _iic_add_one;
        private string reg_Add_32;
        private string reg_Val_32;

        public string Reg_Add_32
        {
            get { return reg_Add_32; }
            set
            {
                if (reg_Add_32 != value)
                {
                    reg_Add_32 = InsertSpaces(value);
                    OnPropertyChanged(nameof(Reg_Add_32));
                }
            }
        }

        public string Reg_Val_32
        {
            get { return reg_Val_32; }
            set
            {
                if (reg_Val_32 != value)
                {
                    reg_Val_32 = InsertSpaces_Val(value);
                    OnPropertyChanged(nameof(Reg_Val_32));
                }
            }
        }
        public string Reg_Add_One
        {
            get { return _reg_add_one; }
            set
            {
                if (_reg_add_one != value)
                {
                    _reg_add_one = InsertSpaces(value);
                    OnPropertyChanged();
                }
            }
        }

        public string Reg_Add_Two
        {
            get { return _reg_add_two; }
            set
            {
                if (_reg_add_two != value)
                {
                    _reg_add_two = InsertSpaces(value);
                    OnPropertyChanged();
                }
            }
        }

        public string Reg_Add_Three
        {
            get { return _reg_add_three; }
            set
            {
                if (_reg_add_three != value)
                {
                    _reg_add_three = InsertSpaces(value);
                    OnPropertyChanged();
                }
            }
        }

        public string Reg_Add_Four
        {
            get { return _reg_add_four; }
            set
            {
                if (_reg_add_four != value)
                {
                    _reg_add_four = InsertSpaces(value);
                    OnPropertyChanged();
                }
            }
        }

        public string IIC_Add_One
        {
            get { return _iic_add_one; }
            set
            {
                if (_iic_add_one != value)
                {
                    _iic_add_one = InsertSpaces(value);
                    OnPropertyChanged();
                }
            }
        }


        public MainWindow()
        {

            InitializeComponent();
            DataContext = this;
            dispatcher = Application.Current.Dispatcher;
            pingWorker = new BackgroundWorker();
            pingWorker.DoWork += PingWorker_DoWork;
            pingWorker.RunWorkerCompleted += PingWorker_RunWorkerCompleted;
            Closing += MainWindow_Closing; // 添加Closing事件处理程序
            Reg_Add_One = "80500137";
            Reg_Add_Two = "80500137";
            Reg_Add_Three = "80500137";
            Reg_Add_Four = "80500137";
            IIC_Add_One = "2000";
            Reg_Add_32 = "80500138";
            Reg_Val_32 = "00000000";
        }


        public event PropertyChangedEventHandler PropertyChanged;

        private string InsertSpaces(string input)
        {
            // 移除所有空格
            string trimmedInput = input.Replace(" ", "");

            // 在每4个字符后插入空格
            string result = "";
            for (int i = 0; i < trimmedInput.Length; i++)
            {
                if (i > 0 && i % 4 == 0)
                {
                    result += " ";
                }
                result += trimmedInput[i];
            }

            return result;
        }

        private string InsertSpaces_Val(string input)
        {
            // 移除所有空格
            string trimmedInput = input.Replace(" ", "");

            // 在每4个字符后插入空格
            string result = "";
            for (int i = 0; i < trimmedInput.Length; i++)
            {
                if (i > 0 && i % 2 == 0)
                {
                    result += " ";
                }
                result += trimmedInput[i];
            }

            return result;
        }


        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            CloseAdb();
            tokenSource?.Cancel();
        }

        private void PingWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            StartLogcatBtn.IsEnabled = true;
            StopLogcatBtn.IsEnabled = false;
        }
        private StringBuilder logcatBuilder = new StringBuilder();
        private static List<string> logcatList = new List<string>();
        private static List<LogcatModel> logcatModels = new List<LogcatModel>();

        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = "cmd.exe",
            Arguments = $"/c {command_log}",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
            WorkingDirectory = adbPath
        };

        private void PingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            CancellationToken token = (CancellationToken)e.Argument;
            using (Process process = Process.Start(startInfo))
            {
                while (!token.IsCancellationRequested)
                {

                    string output = process.StandardOutput.ReadLine();
                    if (string.IsNullOrEmpty(output)) continue;
                    if (!output.Contains("RegAddr") && !output.Contains("Values")) continue;



                    Match match = Regex.Match(output, @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                    if (match.Success)
                    {
                        string regAddr = match.Groups[1].Value;
                        string value = Convert.ToUInt32( match.Groups[2].Value.Replace("0x",""),16).ToString("X2");
                        if (output.ToLower().Contains("read"))
                        {
                            if (output.ToLower().Contains("isp"))
                            {
                                logcatList.Add($"读 ISP RegAddr:{regAddr} Values:0x{value}");
                                logcatModels.Add(new LogcatModel() { Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"), RWText = "ISP", RegAddr = regAddr, Values = value, Operation = "读" });
                            }
                           else if (output.ToLower().Contains("sensor"))
                            {
                                logcatList.Add($"读 Sensor RegAddr:{regAddr} Values:0x{value}");
                                logcatModels.Add(new LogcatModel() { Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"), RWText = "Sensor", RegAddr = regAddr, Values = value, Operation = "读" });
                            }
                            else
                            {
                                logcatList.Add($"读  RegAddr:{regAddr} Values:0x{value}");
                            }
                           
                        }
                        if (output.ToLower().Contains("write"))
                        {
                            if (output.ToLower().Contains("isp"))
                            {
                                logcatList.Add($"写 ISP RegAddr:{regAddr} Values:0x{value}");
                                logcatModels.Add(new LogcatModel() { Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"), RWText = "ISP", RegAddr = regAddr, Values = value, Operation = "写" });
                            }
                            else if (output.ToLower().Contains("sensor"))
                            {
                                logcatList.Add($"写 Sensor RegAddr:{regAddr} Values:0x{value}");
                                logcatModels.Add(new LogcatModel() { Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"), RWText = "Sensor", RegAddr = regAddr, Values = value, Operation = "写" });
                            }
                            else
                            {
                                logcatList.Add($"写  RegAddr:{regAddr} Values:0x{value}");
                            }
                        }
                       
                    }
                    else
                    {
                        continue;
                    }

                    Dispatcher.Invoke(() =>
                    {
                        try
                        {
                            logcatTxt.Text = string.Join("\r\n", logcatList);

                            // 获取TextBox中最后一行的索引
                            int lastLineIndex = logcatTxt.GetLastVisibleLineIndex();

                            // 滚动到最后一行
                            logcatTxt.ScrollToLine(lastLineIndex);
                        }
                        catch
                        {
                            //logcatTxt 空的情况出现 这里直接跳过  无法滚动到最后一行
                        }
                    });

                 
                        if (logcatList.Count > 10)
                        {
                       
                            //logcatList.Clear();
                            Dispatcher.Invoke(() => { logcatTxt.Text = ""; logcatList = new List<string>(); });
                            
                        }
                  
                  

                }

                if (!process.HasExited)
                {
                    process.Kill();
                }

            }

        }


     
        string command_main_switch_s = "adb shell setprop vendor.extcamera.xxw.ispdebug 1";
        string command_main_switch_e = "adb shell setprop vendor.extcamera.xxw.ispdebug 0";
        string command_R = "adb shell setprop vendor.extcamera.xxw.ispregctrl";
        static string command_log = "adb shell logcat";

        private Dispatcher dispatcher;


        static  string adbPath = $"{AppDomain.CurrentDomain.BaseDirectory}adbTool";

        private BackgroundWorker pingWorker;
        private CancellationTokenSource tokenSource;
        private bool isWant = true;
        private  void reg_Btn_Read_Click(object sender, RoutedEventArgs e)
        {

            Button button = (Button)sender;
            string buttonName = button.Name;
            button.IsEnabled = false;
            // 根据按钮名称执行相应的读取操作
            if (buttonName == "reg_Btn1_Read")
            {
                // 执行 Reg_Add_One 的读取操作
                string regAdd = Reg_Add_One.Replace(" ", "");
                ExecuteOperationAsync("读", 0, Reg_Add_One.Replace(" ", ""), "00", reg_val_txt);
                // 在需要调用的地方
                isWant = true;
                Task task = Task.Run(() =>
                {
                    while (isWant)
                    {
                        try
                        {
                            lock (logcatList)
                            {

                                if (logcatList.Count == 0) continue;
                                var lastLogcatItem = logcatList.LastOrDefault(c => c.Contains("ISP") && c.Contains($"RegAddr"));
                                if (lastLogcatItem != null)
                                {
                                    Match match = Regex.Match(lastLogcatItem, @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    //Match match = Regex.Match(logcatList.Where(c => c.Contains($"RegAddr:")).Last(), @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    if (match.Success)
                                    {
                                        string regAddr = match.Groups[1].Value;
                                        string value = match.Groups[2].Value;

                                        Dispatcher.Invoke(() =>
                                        {
                                            if (regAddr.ToLower().Contains(Reg_Add_One.Replace(" ", "")))
                                            {
                                                reg_val_txt.Text = value.Replace("0x", "");
                                                isWant = false;

                                            }
                                           
                                        });

                                    }
                                }

                            }
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(1);
                            continue;
                        }
                    }
                });

            }
            else if (buttonName == "reg_Btn2_Read")
            {
                // 执行 Reg_Add_Two 的读取操作
                string regAdd = Reg_Add_Two.Replace(" ", "");

                ExecuteOperationAsync("读", 0, Reg_Add_Two.Replace(" ", ""), "00", reg_val1_txt);
                // 在需要调用的地方
                isWant = true;
                Task task = Task.Run(() =>
                {
                    while (isWant)
                    {
                        try
                        {
                            lock (logcatList)
                            {

                                if (logcatList.Count == 0) continue;
                                var lastLogcatItem = logcatList.LastOrDefault(c => c.Contains("ISP") && c.Contains($"RegAddr"));
                                if (lastLogcatItem != null)
                                {
                                    Match match = Regex.Match(lastLogcatItem, @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    //Match match = Regex.Match(logcatList.Where(c => c.Contains($"RegAddr:")).Last(), @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    if (match.Success)
                                    {
                                        string regAddr = match.Groups[1].Value;
                                        string value = match.Groups[2].Value;

                                        Dispatcher.Invoke(() =>
                                        {
                                            if (regAddr.ToLower().Contains(Reg_Add_Two.Replace(" ", "")))
                                            {
                                                reg_val1_txt.Text = value.Replace("0x", "");
                                                isWant = false;
                                            }
                                        });

                                    }
                                }

                            }
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(1);
                            continue;
                        }
                    }
                });
            }
            else if (buttonName == "reg_Btn3_Read")
            {
                // 执行 Reg_Add_Three 的读取操作
                string regAdd = Reg_Add_Three.Replace(" ", "");

                ExecuteOperationAsync("读", 0, Reg_Add_Three.Replace(" ", ""), "00", reg_val2_txt);
                // 在需要调用的地方
                isWant = true;
                Task task = Task.Run(() =>
                {
                    while (isWant)
                    {
                        try
                        {
                            lock (logcatList)
                            {

                                if (logcatList.Count == 0) continue;
                                var lastLogcatItem = logcatList.LastOrDefault(c => c.Contains("ISP") && c.Contains($"RegAddr"));
                                if (lastLogcatItem != null)
                                {
                                    Match match = Regex.Match(lastLogcatItem, @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    //Match match = Regex.Match(logcatList.Where(c => c.Contains($"RegAddr:")).Last(), @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    if (match.Success)
                                    {
                                        string regAddr = match.Groups[1].Value;
                                        string value = match.Groups[2].Value;

                                        Dispatcher.Invoke(() =>
                                        {
                                           if (regAddr.ToLower().Contains(Reg_Add_Three.Replace(" ", "")))
                                            {
                                                reg_val2_txt.Text = value.Replace("0x", "");
                                                isWant = false;
                                            }
                                        });

                                    }
                                }

                            }
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(1);
                            continue;
                        }
                    }
                });
            }
            else if (buttonName == "reg_Btn4_Read")
            {
                // 执行 Reg_Add_Four 的读取操作
                string regAdd = Reg_Add_Four;

                ExecuteOperationAsync("读", 0, Reg_Add_Four.Replace(" ", ""), "00", reg_val3_txt);
                // 在需要调用的地方
                isWant = true;
                Task task = Task.Run(() =>
                {
                    while (isWant)
                    {
                        try
                        {
                            lock (logcatList)
                            {

                                if (logcatList.Count == 0) continue;
                                var lastLogcatItem = logcatList.LastOrDefault(c => c.Contains("ISP") && c.Contains($"RegAddr"));
                                if (lastLogcatItem != null)
                                {
                                    Match match = Regex.Match(lastLogcatItem, @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    //Match match = Regex.Match(logcatList.Where(c => c.Contains($"RegAddr:")).Last(), @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    if (match.Success)
                                    {
                                        string regAddr = match.Groups[1].Value;
                                        string value = match.Groups[2].Value;

                                        Dispatcher.Invoke(() =>
                                        {
                                            if (regAddr.ToLower().Contains(Reg_Add_Four.Replace(" ", "")))
                                            {
                                                reg_val3_txt.Text = value.Replace("0x", "");
                                                isWant = false;
                                            }
                                        });

                                    }
                                }

                            }
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(1);
                            continue;
                        }
                    }
                });
            }
            button.IsEnabled = true;

         
        }

        private  void reg_Btn_Write_Click(object sender, RoutedEventArgs e)
        {

            Button button = (Button)sender;
            string buttonName = button.Name;
            button.IsEnabled = false;
            // 根据按钮名称执行相应的写入操作
            if (buttonName == "reg_Btn1_Write")
            {
                // 执行 Reg_Add_One 的写入操作
                string regAdd = Reg_Add_One;
                ExecuteOperationAsync("写", 1, Reg_Add_One.Replace(" ", ""), "00", reg_val_txt);
            }
            else if (buttonName == "reg_Btn2_Write")
            {
                // 执行 Reg_Add_Two 的写入操作
                string regAdd = Reg_Add_Two; 
                ExecuteOperationAsync("写", 1, Reg_Add_Two.Replace(" ", ""), "00", reg_val1_txt);
            }
            else if (buttonName == "reg_Btn3_Write")
            {
                // 执行 Reg_Add_Three 的写入操作
                string regAdd = Reg_Add_Three;
                ExecuteOperationAsync("写", 1, Reg_Add_Three.Replace(" ", ""), "00", reg_val2_txt);
            }
            else if (buttonName == "reg_Btn4_Write")
            {
                // 执行 Reg_Add_Four 的写入操作
                string regAdd = Reg_Add_Four;
                ExecuteOperationAsync("写", 1, Reg_Add_Four.Replace(" ", ""), "00", reg_val3_txt);
            }

            button.IsEnabled = true;
        }

       

        // 将字符串从GB2312转换为UTF-8，若转换失败，返回原始字符串
        public static string ConvertToUTF8(string gb2312String)
        {
            try
            {
                byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(gb2312String);
                return Encoding.UTF8.GetString(bytes);
            }
            catch
            {
                return gb2312String;
            }
        }


      

        private void ExecuteOperationAsync(string operation,int operNO,string addr,string iD, TextBox textVal)
        {
           

            if (operation == "读")
            {
                AddMessage("开始执行->读操作");
            }
            else if (operation == "写")
            {
                AddMessage("开始执行->写操作");
            }
            string adbCommand = $"{command_R} \"{operNO},{addr},{textVal.Text},{id_Txt.Text}\"";
            var com_str =  CmdHelper.ExecuteCommand(adbCommand, adbPath);
            AddMessage(com_str);
           

        }

        private StringBuilder messageBuilder = new StringBuilder();
        private int lineCount = 0;

        public void AddMessage(string message)
        {
            // 添加新的消息到 StringBuilder
            string formattedMessage = $"{DateTime.Now:HH:mm:ss} - {message}";
            messageBuilder.AppendLine(formattedMessage);
            lineCount++;

            // 检查行数是否超过10000
            if (lineCount > 1000)
            {
                // 清空 StringBuilder
                messageBuilder.Clear();
                lineCount = 0;
                Dispatcher.Invoke(() => { msgTxt.Text = ""; });
            }

            dispatcher.Invoke(() => {
                
                try
                {
                    msgTxt.Text = messageBuilder.ToString();
                    // 获取TextBox中最后一行的索引
                    int lastLineIndex = msgTxt.GetLastVisibleLineIndex();
                    // 滚动到最后一行
                    msgTxt.ScrollToLine(lastLineIndex);
                }
                catch
                {
                    //logcatTxt 空的情况出现 这里直接跳过  无法滚动到最后一行
                }
            });

        }

      

        private void StartLogcatBtn_Click(object sender, RoutedEventArgs e)
        {

            StartLogcatBtn.IsEnabled = false;
            StopLogcatBtn.IsEnabled = true;
            //添加一条开启命令
            var com_str = CmdHelper.ExecuteCommand(command_main_switch_s,adbPath);
            AddMessage(com_str);
            tokenSource = new CancellationTokenSource();

            CancellationToken token = tokenSource.Token;

            pingWorker.RunWorkerAsync(token);


        }

        private void CloseAdb()
        {
            //// 获取所有名为"adb"的进程
            //Process[] processes = Process.GetProcessesByName("adb");
            //// 关闭所有adb进程
            //foreach (Process process in processes)
            //{
            //    process.Kill();
            //    Thread.Sleep(10);
            //}

            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = "taskkill";
            psi.Arguments = "/F /IM adb.exe";  // 结束名为"adb"的进程
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = true;
            Process.Start(psi);
        }

        private void StopLogcatBtn_Click(object sender, RoutedEventArgs e)
        {

            CloseAdb();
            tokenSource?.Cancel();
            StopLogcatBtn.IsEnabled = false;
            isWant = false;
            logcatList.Clear();
        }

        private  void iic_Btn_Read_Click(object sender, RoutedEventArgs e)
        {
            iic_Btn_Read.IsEnabled = false;
            //_ = await CmdHelper.ExecuteCommandAsync(command_main_switch_s, adbPath);
            ExecuteOperationAsync("读", 2, iic_add_txt.Text, id_Txt.Text, iic_val_txt);
            // 在需要调用的地方
            isWant = true;
            Task task = Task.Run(() =>
            {
                while (isWant)
                {
                    try
                    {
                        lock (logcatList)
                        {

                            if (logcatList.Count == 0) continue;
                            Match match = Regex.Match(logcatList.Where(c =>c.Contains("Sensor") && c.Contains($"RegAddr")).Last(), @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                            if (match.Success)
                            {
                                string regAddr = match.Groups[1].Value;
                                string value = match.Groups[2].Value;

                                Dispatcher.Invoke(() =>
                                {
                                    if (regAddr.Contains(iic_add_txt.Text))
                                    {
                                        iic_val_txt.Text = value.Replace("0x","");
                                        isWant = false;
                                     
                                    }
                                });

                            }

                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            });
            iic_Btn_Read.IsEnabled = true;
        }

        private  void iic_Btn_Write_Click(object sender, RoutedEventArgs e)
        {
            iic_Btn_Write.IsEnabled = false;
            ExecuteOperationAsync("写", 3, iic_add_txt.Text, id_Txt.Text, iic_val_txt);
            //_ = await CmdHelper.ExecuteCommandAsync(command_main_switch_e, adbPath);
            iic_Btn_Write.IsEnabled = true;
        }

        private void a3mode_start_Click(object sender, RoutedEventArgs e)
        {
            a3mode_start.IsEnabled = false;
            var com_str = CmdHelper.ExecuteCommand(ConvertToUTF8("adb shell setprop vendor.extCamera.xxw.3amode 1"), adbPath);
            AddMessage(com_str);
            a3mode_start.IsEnabled = true;
        }

        private void a3mode_stop_Click(object sender, RoutedEventArgs e)
        {
            a3mode_stop.IsEnabled = false;
            var com_str = CmdHelper.ExecuteCommand(ConvertToUTF8("adb shell setprop vendor.extCamera.xxw.3amode 0"), adbPath);
            AddMessage(com_str);
            a3mode_stop.IsEnabled = true;
        }


        List<AddrHelp> addrHelps = new List<AddrHelp>();
        public static UInt32 addr;//全局变量
        public static UInt32 addrV;
        /// <summary>
        /// 寄存器文件读
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void RegiFileRead_Click(object sender, RoutedEventArgs e)
        {
            RegiFileRead.IsEnabled = false;
           

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    addrHelps = new List<AddrHelp>();
                    string txtFilePath = openFileDialog.FileName;
                    StreamReader reader = new StreamReader(txtFilePath, Encoding.GetEncoding("gb2312"));
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine().Trim();

                        if (line.Contains("//"))//去除注释
                        {
                            line = line.Remove(line.IndexOf("//"));
                        }

                        line = line.Replace('，', ',').Replace(" ", "");//全换成英文逗号，去掉空格

                        if (string.IsNullOrEmpty(line))
                        {
                            continue; // Skip empty lines
                        }

                        string[] values = line.Split(',');

                        if (values.Length >= 2)
                        {
                            uint regAddress = Convert.ToUInt32(values[0].Trim(), 16);
                            uint regData = Convert.ToUInt32(values[1].Trim(), 16);
                            AddrHelp model = new AddrHelp(regAddress,regData);
                            model.ID = "00";
                            model.ReadNO = "0";
                            model.WriteNo = "1";
                            if (regAddress == 0xfffd)
                            {
                                addr = (regData & 0xff);
                            }
                            else if (regAddress == 0xfffe)
                            {
                                addrV = (regData & 0xff);
                            }
                            else
                            {
                                model.BaseAddr = (addr << 8) + ((addrV & 0xff));
                                addrHelps.Add(model);
                            }
                          
                        }
                    }
                    reader.Close();

                    msgTxt.Text = "";
                   var  cancellationTokenSource = new CancellationTokenSource();

                    //执行下发指令
                    foreach (var item in addrHelps)
                    {
                        var isRegWant = true;
                        CmdHelper.ExecuteCommand(item.GetCommand, adbPath);
                        Thread.Sleep(250);
                        CmdHelper.ExecuteCommand(item.GetCommand, adbPath);
                        Thread.Sleep(250);
                        //监控数据
                        await Task.Run(() =>
                        {
                            while (isRegWant && !cancellationTokenSource.Token.IsCancellationRequested)
                            {
                                try
                                {
                                    lock (logcatList)
                                    {
                                        if (!isRegWant || cancellationTokenSource.Token.IsCancellationRequested)
                                        {
                                            continue;
                                        }

                                        Thread.Sleep(10);
                                        Match match = Regex.Match(logcatList.Where(c => c.Contains("ISP") && c.Contains($"RegAddr")).Last(), @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                        if (match.Success)
                                        {
                                            string regAddr = match.Groups[1].Value;
                                            string value = match.Groups[2].Value;
                                            if (regAddr.ToLower().Contains(item.Addr.ToLower()))
                                            {
                                                item.Data = Convert.ToUInt32(value.Replace("0x", ""), 16);
                                                Dispatcher.Invoke(() =>
                                                {
                                                    msgTxt.Text += $"{DateTime.Now:HH:mm:ss} -地址： {regAddr} 数据：{value}\r\n";
                                                    int lastLineIndex = msgTxt.GetLastVisibleLineIndex();
                                                    // 滚动到最后一行
                                                    msgTxt.ScrollToLine(lastLineIndex);
                                                });
                                                isRegWant = false;
                                            }
                                        }
                                    }

                                }
                                catch (Exception)
                                {
                                    continue;
                                }

                            }
                        });
                    }
                    cancellationTokenSource?.Cancel();

                    //保存数据
                    // 获取文件名
                    string fileName = System.IO.Path.GetFileName(txtFilePath);

                    // 保存到桌面
                    string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    string destinationPath = System.IO.Path.Combine(desktopPath, $"adb_reg_{fileName}");
                    
                    using (StreamWriter writer = new StreamWriter(destinationPath))
                    {
                        var baseAddr = string.Empty;
                        foreach (var item in addrHelps)
                        {
                            if (string.IsNullOrEmpty(baseAddr)|| baseAddr != item.BaseAddr.ToString("X"))
                            {
                                writer.Write($" 0xfffd,0x{(item.BaseAddr>>8 &0xff).ToString("X2")},\r\n");
                                writer.Write($" 0xfffe,0x{(item.BaseAddr & 0xff).ToString("X2")},\r\n");
                                baseAddr = item.BaseAddr.ToString("X");
                            }
                                writer.Write($"0x{item.Address.ToString("X4")},0x{item.Data.ToString("X2")},\r\n");
                            
                          
                        }
                      
                    }

                    MessageBox.Show($"读数据已完成  路径：{destinationPath}");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            RegiFileRead.IsEnabled = true;
        }
        /// <summary>
        /// 寄存器文件写
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void RegFileWrit_Click(object sender, RoutedEventArgs e)
        {
            RegFileWrit.IsEnabled = false;

             OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    addrHelps = new List<AddrHelp>();
                    string txtFilePath = openFileDialog.FileName;
                    StreamReader reader = new StreamReader(txtFilePath, Encoding.GetEncoding("gb2312"));
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine().Trim();

                        if (line.Contains("//"))//去除注释
                        {
                            line = line.Remove(line.IndexOf("//"));
                        }

                        line = line.Replace('，', ',').Replace(" ", "");//全换成英文逗号，去掉空格

                        if (string.IsNullOrEmpty(line))
                        {
                            continue; // Skip empty lines
                        }

                        string[] values = line.Split(',');

                        if (values.Length >= 2)
                        {
                            uint regAddress = Convert.ToUInt32(values[0].Trim(), 16);
                            uint regData = Convert.ToUInt32(values[1].Trim(), 16);
                            AddrHelp model = new AddrHelp(regAddress, regData);
                            model.ID = "00";
                            model.ReadNO = "0";
                            model.WriteNo = "1";
                            if (regAddress == 0xfffd)
                            {
                                addr = (regData & 0xff);
                            }
                            else if (regAddress == 0xfffe)
                            {
                                addrV = (regData & 0xff);
                            }
                            else
                            {
                                model.BaseAddr = (addr << 8) + ((addrV & 0xff));
                                addrHelps.Add(model);
                            }

                        }
                    }
                    reader.Close();

                    msgTxt.Text = "";

                    await Task.Run(() =>
                    {
                        //执行下发指令
                        foreach (var item in addrHelps)
                        {
                            CmdHelper.ExecuteCommand(item.SetCommand, adbPath);
                            Thread.Sleep(150);
                            CmdHelper.ExecuteCommand(item.SetCommand, adbPath);
                            Thread.Sleep(150);
                            //监控数据
                            Dispatcher.Invoke(() =>
                            {
                                msgTxt.Text += $"{DateTime.Now:HH:mm:ss} 下发寄存器数据 地址：{item.Addr} 数据：{item.Data.ToString("X2")}\r\n";
                                int lastLineIndex = msgTxt.GetLastVisibleLineIndex();
                                // 滚动到最后一行
                                msgTxt.ScrollToLine(lastLineIndex);
                            });
                        }
                    });
                    MessageBox.Show("下发寄存器数据->已完成");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            RegFileWrit.IsEnabled = true;
        }

        List<SensorHelp>  sensorHelps = new List<SensorHelp>();
        public static UInt32 SensorId;//全局变量
        /// <summary>
        /// IIC 文件读
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void IICFileRead_Click(object sender, RoutedEventArgs e)
        {
            IICFileRead.IsEnabled = false;


            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    sensorHelps = new List<SensorHelp>();
                    string txtFilePath = openFileDialog.FileName;
                    StreamReader reader = new StreamReader(txtFilePath, Encoding.GetEncoding("gb2312"));
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine().Trim();

                        if (line.Contains("//"))//去除注释
                        {
                            line = line.Remove(line.IndexOf("//"));
                        }

                        line = line.Replace('，', ',').Replace(" ", "");//全换成英文逗号，去掉空格

                        if (string.IsNullOrEmpty(line))
                        {
                            continue; // Skip empty lines
                        }

                        string[] values = line.Split(',');

                        if (values.Length >= 2)
                        {
                            uint regAddress = Convert.ToUInt32(values[0].Trim(), 16);
                            uint regData = Convert.ToUInt32(values[1].Trim(), 16);
                            SensorHelp model = new SensorHelp(regAddress, regData);
                            model.ReadNO = "2";
                            model.WriteNo = "3";
                            if (regAddress == 0xfff2 || regAddress == 0xfffe || regAddress == 0xffff)
                            {
                                continue;
                            }
                            else if (regAddress == 0xfff8)
                            {
                                SensorId = (regData & 0xff);
                            }
                            else
                            {
                                model.ID = SensorId.ToString("X2");
                                sensorHelps.Add(model);
                            }

                        }
                    }
                    reader.Close();

                    msgTxt.Text = "";
                    if (sensorHelps.Exists(c => c.ID =="00"))
                    {
                        MessageBox.Show("IIC 不存在sensor_i2c_id  请补充0xfff8");
                        IICFileRead.IsEnabled = true;
                        return;
                    }
                    var cancellationTokenSource = new CancellationTokenSource();

                    //执行下发指令
                    foreach (var item in sensorHelps)
                    {
                        var isRegWant = true;
                        CmdHelper.ExecuteCommand(item.GetCommand, adbPath);
                        Thread.Sleep(150);
                        CmdHelper.ExecuteCommand(item.GetCommand, adbPath);
                        Thread.Sleep(150);
                        //监控数据
                        await Task.Run(() =>
                        {
                            while (isRegWant && !cancellationTokenSource.Token.IsCancellationRequested)
                            {
                                try
                                {
                                    lock (logcatList)
                                    {
                                        if (!isRegWant || cancellationTokenSource.Token.IsCancellationRequested)
                                        {
                                            continue;
                                        }

                                        Thread.Sleep(10);
                                        Match match = Regex.Match(logcatList.Where(c => c.Contains("Sensor") && c.Contains($"RegAddr")).LastOrDefault(), @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                        if (match.Success)
                                        {
                                            string regAddr = match.Groups[1].Value;
                                            string value = match.Groups[2].Value;
                                            if (regAddr.ToLower().Contains(item.Address.ToString("X").ToLower()))
                                            {
                                                item.Data = Convert.ToUInt32(value.Replace("0x", ""), 16);
                                                Dispatcher.Invoke(() =>
                                                {
                                                    msgTxt.Text += $"{DateTime.Now:HH:mm:ss} 读取  ID:{item.ID} 地址： {item.Address.ToString("X4")} 数据：{item.Data.ToString("X2")}\r\n";
                                                    int lastLineIndex = msgTxt.GetLastVisibleLineIndex();
                                                    // 滚动到最后一行
                                                    msgTxt.ScrollToLine(lastLineIndex);
                                                });
                                                isRegWant = false;
                                            }
                                        }
                                    }

                                }
                                catch (Exception)
                                {
                                    continue;
                                }

                            }
                        });
                    }
                    cancellationTokenSource?.Cancel();

                    // 获取文件名
                    string fileName = System.IO.Path.GetFileName(txtFilePath);

                    // 保存到桌面
                    string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    string destinationPath = System.IO.Path.Combine(desktopPath, $"adb_iic_{fileName}");

                    using (StreamWriter writer = new StreamWriter(destinationPath))
                    {
                        var baseAddr = string.Empty;
                        foreach (var item in sensorHelps)
                        {
                            if (string.IsNullOrEmpty(baseAddr) || baseAddr != item.ID)
                            {
                                writer.Write($" 0xfff8,0x{item.ID},\r\n");
                                baseAddr = item.ID;
                            }
                            writer.Write($"0x{item.Address.ToString("X4")},0x{item.Data.ToString("X2")},\r\n");


                        }

                    }
                    MessageBox.Show($"读IIC数据已完成  文件路径：{destinationPath}");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            IICFileRead.IsEnabled = true;
        }
        /// <summary>
        /// IIC 文件写
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void IICFileWrit_Click(object sender, RoutedEventArgs e)
        {
            IICFileWrit.IsEnabled = false;
            
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    sensorHelps = new List<SensorHelp>();
                    string txtFilePath = openFileDialog.FileName;
                    StreamReader reader = new StreamReader(txtFilePath, Encoding.GetEncoding("gb2312"));
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine().Trim();

                        if (line.Contains("//"))//去除注释
                        {
                            line = line.Remove(line.IndexOf("//"));
                        }

                        line = line.Replace('，', ',').Replace(" ", "");//全换成英文逗号，去掉空格

                        if (string.IsNullOrEmpty(line))
                        {
                            continue; // Skip empty lines
                        }

                        string[] values = line.Split(',');

                        if (values.Length >= 2)
                        {
                            uint regAddress = Convert.ToUInt32(values[0].Trim(), 16);
                            uint regData = Convert.ToUInt32(values[1].Trim(), 16);
                            SensorHelp model = new SensorHelp(regAddress, regData);
                            model.ReadNO = "2";
                            model.WriteNo = "3";
                           
                            if (regAddress == 0xfff2 || regAddress == 0xfffe|| regAddress == 0xffff)
                            {
                                continue;
                            }else if(regAddress == 0xfff8)
                            {
                                SensorId = (regData & 0xff);
                            }
                            else
                            {
                                model.ID = SensorId.ToString("X2");
                                sensorHelps.Add(model);
                            }

                        }
                    }
                    reader.Close();

                    msgTxt.Text = "";
                    if (sensorHelps.Exists(c => c.ID == "00"))
                    {
                        MessageBox.Show("IIC 不存在sensor_i2c_id  请补充0xfff8");
                        IICFileRead.IsEnabled = true;
                        return;
                    }

                    //执行下发指令
                    //foreach (var item in sensorHelps)
                    //{
                    //    CmdHelper.ExecuteCommand(item.SetCommand, adbPath);
                    //    Thread.Sleep(250);
                    //    CmdHelper.ExecuteCommand(item.SetCommand, adbPath);
                    //    Thread.Sleep(250);
                    //    //监控数据
                    //    Dispatcher.Invoke(() =>
                    //    {
                    //        msgTxt.Text += $"{DateTime.Now:HH:mm:ss} 下发  ID:{item.ID} 地址： {item.Address.ToString("X4")} 数据：{item.Data.ToString("X2")}\r\n";
                    //        int lastLineIndex = msgTxt.GetLastVisibleLineIndex();
                    //        // 滚动到最后一行
                    //        msgTxt.ScrollToLine(lastLineIndex);
                    //    });

                    //}

                    await Task.Run(() =>
                    {
                        foreach (var item in sensorHelps)
                        {
                            CmdHelper.ExecuteCommand(item.SetCommand, adbPath);
                            Thread.Sleep(250);
                            CmdHelper.ExecuteCommand(item.SetCommand, adbPath);
                            Thread.Sleep(250);
                            // 监控数据
                            Dispatcher.Invoke(() =>
                            {
                                msgTxt.Text += $"{DateTime.Now:HH:mm:ss} 下发  ID:{item.ID} 地址： {item.Address.ToString("X4")} 数据：{item.Data.ToString("X2")}\r\n";
                                int lastLineIndex = msgTxt.GetLastVisibleLineIndex();
                                // 滚动到最后一行
                                msgTxt.ScrollToLine(lastLineIndex);
                            });
                        }
                    });
                    MessageBox.Show("下发IIC数据->已完成");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            IICFileWrit.IsEnabled = true;
        }



        string openFile = string.Empty;
        private async void adbGetFileRead_Click(object sender, RoutedEventArgs e)
        {
            adbGetFileRead.IsEnabled = false;
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "All Files(*.*)|*.*";

            if (openFileDialog.ShowDialog() == true)
            {

                var com_str = await CmdHelper.ExecuteCommandAsync("adb kill-server", adbPath);
                com_str = await CmdHelper.ExecuteCommandAsync("adb start-server", adbPath);

                com_str = await CmdHelper.ExecuteCommandAsync("adb devices", adbPath);
                string pattern = @"List of devices attached\r?\n(?<devices>(\w+)\s+(device)?)";
                MatchCollection matches = Regex.Matches(com_str, pattern);
                if (matches.Count > 0)
                {
                    foreach (Match match1 in matches)
                    {
                        AddMessage($"检查到设备名称：{match1.Groups[1].Value}");
                    }
                }
                else
                {
                    AddMessage($"未检查到设备！请检查设备是否在线！");
                    adbGetFileRead.IsEnabled = true;
                    return;
                }
                Thread.Sleep(1);
                openFile = System.IO.Path.GetDirectoryName(openFileDialog.FileName);
                string adbGet = $"adb pull /vendor/lib64/libcamera_daemon.so {openFile}";
                com_str = await CmdHelper.ExecuteCommandAsync(adbGet, adbPath);
                AddMessage(com_str);
            }
            adbGetFileRead.IsEnabled = true;
        }

        private async void adbSetFileWrit_Click(object sender, RoutedEventArgs e)
        {
            adbSetFileWrit.IsEnabled = false;
            //关闭监控
            StopLogcatBtn_Click(null, null);
             OpenFileDialog openFileDialog = new OpenFileDialog();
            if (!string.IsNullOrEmpty(openFile))
            {
                openFileDialog.InitialDirectory = openFile;
            }
           
            openFileDialog.Filter = "TXT Files(*.so)|*.so|All Files(*.*)|*.*";
            if (openFileDialog.ShowDialog() == true)
            {
                var com_str = await CmdHelper.ExecuteCommandAsync("adb kill-server", adbPath);
                com_str = await CmdHelper.ExecuteCommandAsync("adb start-server", adbPath);
                com_str = await CmdHelper.ExecuteCommandAsync("adb devices", adbPath);
                string pattern = @"List of devices attached\r?\n(?<devices>(\w+)\s+(device)?)";
                MatchCollection matches = Regex.Matches(com_str, pattern);
                if (matches.Count > 0)
                {
                    foreach (Match match1 in matches)
                    {
                        AddMessage($"检查到设备名称：{match1.Groups[1].Value}");
                    }
                }
                else
                {
                    AddMessage($"未检查到设备！请检查设备是否在线！");
                    adbSetFileWrit.IsEnabled = true;
                    return;
                }
                Thread.Sleep(1);
                com_str = await CmdHelper.ExecuteCommandAsync("adb wait-for-device", adbPath);
                AddMessage(com_str);
                Thread.Sleep(1);
                com_str = await CmdHelper.ExecuteCommandAsync("adb root", adbPath);
                if (!com_str.Contains("running"))
                {
                    AddMessage("执行Root 权限失败 无法已root身份运行！");
                    adbSetFileWrit.IsEnabled = true;
                    return;
                }
                else
                {
                    AddMessage("执行Root 权限成功 adb已root身份运行！");
                }
                Thread.Sleep(1);
                com_str = await CmdHelper.ExecuteCommandAsync("adb wait-for-device", adbPath);
                //AddMessage(com_str);
                Thread.Sleep(1);
                com_str = await CmdHelper.ExecuteCommandAsync("adb remount", adbPath);
                if (!com_str.Contains("succeeded"))
                {
                    AddMessage("重新装载失败！");
                    adbSetFileWrit.IsEnabled = true;
                    return;
                }
                else
                {
                    AddMessage("重新装载成功！");
                }
                string adbSet = $"adb push {openFileDialog.FileName} vendor/lib64/";

                Thread.Sleep(1);
                com_str = await CmdHelper.ExecuteCommandAsync(adbSet, adbPath);
               
                string pushStr = @"\d+ file pushed";
                Match match = Regex.Match(com_str, pushStr);

                if (match.Success)
                {
                    AddMessage($"推送了{match.Value}个文件");
                }
                else
                {
                    AddMessage($"推送失败了！");
                    AddMessage(com_str);
                }
               
            }

            adbSetFileWrit.IsEnabled = true;
        }

        private void upLogcatBtn_Click(object sender, RoutedEventArgs e)
        {
            // 保存到桌面
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string destinationPath = System.IO.Path.Combine(desktopPath, $"adb_监控取值{DateTime.Now.ToString("fff")}.txt");

            using (StreamWriter writer = new StreamWriter(destinationPath))
            {
                List<LogcatModel> uniqueLogcatModels = logcatModels
                                                       .GroupBy(model => model.Date) // 按照Date属性进行分组
                                                       .Select(group => group.First()) // 选择每个分组中的第一个元素
                                                       .ToList();
                foreach (var item in uniqueLogcatModels)
                {
                    writer.Write($"{item.Date} {item.Operation} {item.RWText}  0x{item.RegAddr},0x{item.Values},\r\n");
                }
                logcatModels = new List<LogcatModel>();
            }
            MessageBox.Show($"adb_监控取值  文件路径：{destinationPath}");
        }

        /// <summary>
        /// 32位读
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void reg_Btn5_Read_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            string buttonName = button.Name;
            button.IsEnabled = false;
            bool endsWith048C = Regex.IsMatch(Reg_Add_32, ".*[^048C]$");
            if (endsWith048C)
            {
                MessageBox.Show($"地址不以 0、4、8、c 结尾");
                return;
            }
            var regAdd = Convert.ToUInt32(Reg_Add_32.Replace(" ", ""), 16);
            var regVal = string.Empty;
            for (int i = 0; i < 4; i++)
            {
                var regT =  regAdd + i;
                string adbCommand = $"{command_R} \"0,{regT.ToString("X")},FF,{id_Txt.Text}\"";
                var com_str = CmdHelper.ExecuteCommand(adbCommand, adbPath);
                AddMessage(com_str);
                // 在需要调用的地方
                isWant = true;
                Task task = Task.Run(() =>
                {
                    while (isWant)
                    {
                        try
                        {
                            lock (logcatList)
                            {

                                if (logcatList.Count == 0) continue;
                                var lastLogcatItem = logcatList.LastOrDefault(c => c.Contains("ISP") && c.Contains($"RegAddr"));
                                if (lastLogcatItem != null)
                                {
                                    Match match = Regex.Match(lastLogcatItem, @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    //Match match = Regex.Match(logcatList.Where(c => c.Contains($"RegAddr:")).Last(), @"RegAddr:(0x[0-9a-fA-F]+) Values:(0x[0-9a-fA-F]+)");
                                    if (match.Success)
                                    {
                                        string regAddr = match.Groups[1].Value;
                                        string value = match.Groups[2].Value;

                                        Dispatcher.Invoke(() =>
                                        {
                                            if (regAddr.ToLower().Contains(regT.ToString("x")))
                                            {
                                                regVal += value.Replace("0x", "");
                                                isWant = false;

                                            }

                                        });

                                    }
                                }

                            }
                        }
                        catch (Exception)
                        {
                            Thread.Sleep(1);
                            continue;
                        }
                    }
                });

            }

           
           


            button.IsEnabled = true;
        }
        /// <summary>
        /// 32位写
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void reg_Btn5_Write_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            string buttonName = button.Name;
            button.IsEnabled = false;
            bool endsWith048C = Regex.IsMatch(Reg_Add_32, ".*[^048C]$");
            if (endsWith048C)
            {
                MessageBox.Show($"地址不以 0、4、8、c 结尾");
                return;
            }
            var regAdd = Convert.ToUInt32(Reg_Add_32.Replace(" ", ""), 16);
            var rVal =  Reg_Val_32.Split(' ');
            for (int i = 0; i < rVal.Count(); i++)
            {
                var rT =  regAdd + i;
                string adbCommand = $"{command_R} \"1,{rT.ToString("X")},{rVal.ToString()},00\"";
                var com_str = CmdHelper.ExecuteCommand(adbCommand, adbPath);
                AddMessage(com_str);
            }

           

            button.IsEnabled = true;
        }
    }
}
